import { createFeatureSelector, createSelector } from '@ngrx/store';

import { Layer } from '../../models';
import { OlState, LayerState, getLayerEntities, getLayerLastId } from '../reducers';
import { getOlStateSelector } from './ol.selector';

const getLayerStateSelector = createSelector(getOlStateSelector, (state: OlState) => state.layers);
const getLayerEntitiesSelector = createSelector(getLayerStateSelector, getLayerEntities);
const getAllLayerSelector = createSelector(getLayerEntitiesSelector, (entities: { [id: number]: Layer }) => {
    return Object.keys(entities).map(key => {
        const id = parseInt(key, 10);
        return {
            ...entities[id],
            id
        }
    });
});
const getLayerLastAddSelector = createSelector(getLayerStateSelector, (state: LayerState) => {
    const id = state.lastId;
    let layer: Layer = state.entities[id];
    if(layer) {
        layer = {
            ...layer,
            id
        };
    }
    return layer;
});
const getLayerLastIdSelector = createSelector(getLayerStateSelector, getLayerLastId);

export const layerSelector = {
    getLayerState: getLayerStateSelector,
    getLayerEntities: getLayerEntitiesSelector,
    getAllLayer: getAllLayerSelector,
    getLayerLastAdd: getLayerLastAddSelector,
    getLayerLastId: getLayerLastIdSelector
};
